<route lang="json5">
  {
    style: {
      navigationBarTitleText: '设置',
    },
  }
  </route>

<!-- start -->
<template>
  <view class="container">


    <!-- 用户信息 -->
    <view class="user-info" @click="handleUpload">
      <view class="info-left">
        <text class="info-label">头像</text>
      </view>
      <view class="info-right">
        <image class="avatar" :src="userStore.userInfo.avatar" mode="aspectFill" />

        <uni-icons type="right" size="16" color="#999" />


      </view>
    </view>

    <!-- 基本信息设置 -->
    <view class="menu-group">
      <view class="menu-item" @click="handleNickname">
        <text class="item-label">昵称</text>
        <view class="item-right">
          <text class="item-value">{{ userStore.userInfo.nickname }}</text>
          <!-- <uni-icons type="right" size="16" color="#999"/> -->
        </view>
      </view>
    </view>

    <!-- 安全设置 -->
    <view class="menu-group">
      <view class="menu-item" @click="handlePayPassword">
        <text class="item-label">更换支付密码</text>
        <uni-icons type="right" size="16" color="#999" />
      </view>
    </view>

    <!-- 版本信息 -->
    <view class="menu-group">
      <view class="menu-item">
        <text class="item-label">新版本型号</text>
        <view class="item-right">
          <text class="version">1.3.6</text>
        </view>
      </view>
    </view>

    <!-- 退出按钮 -->
    <view class="logout-wrapper">
      <button class="logout-btn" @click="handleLogout">退出当前账号</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store'
import { postLogoutAPI, getUserIndexAPI, postUploadAPI, postUpdateProfileAPI } from '@/service/index/index'
import { onMounted, ref } from 'vue'

const userStore = useUserStore()
const filePicker = ref(null)

const handleBack = () => {
  uni.navigateBack();
};

const imageStyles = {
  width: 64,
  height: 64,
  border: {
    radius: '50%'
  }
}
const listStyles = {
  // 是否显示边框
  border: true,
  // 是否显示分隔线
  dividline: true,
  // 线条样式
  borderStyle: {
    width: 1,
    color: 'blue',
    style: 'dashed',
    radius: 2
  }
}
const fileLists = [{
  url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao-small.jpg',
  extname: 'png',
  name: 'shuijiao.png'
}]




const handlePayPassword = () => {
  uni.navigateTo({
    url: '/pages/my/find_pay_pass',
  });
};
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确认退出当前账号吗？',
    confirmColor: '#ff6b6b',
    success: (res) => {
      if (res.confirm) {
        postLogoutAPI().then((res) => {
          console.log(res)
          if (res.code === 1) {
            uni.showToast({
              title: '退出成功',
              icon: 'none',
            })
            setTimeout(() => {
              const userInfo = {
                nickname: '',
                avatar: '',
                openid: '',
                token: '',
              }
              useUserStore().setUserInfo(userInfo)
              uni.navigateTo({
                url: '/pages/login/login',
              })
            }, 1000)
          } else {
            uni.showToast({
              title: '退出失败',
              icon: 'none',
            })
          }
        })

      }
    }
  });
};

// Define UserInfo interface
interface UserInfo {
  nickname: string;
  avatar: string;
  openid?: string;
  token?: string;
  [key: string]: any;
}

const userInfo = ref<UserInfo | null>(null)
const getUserInfo = () => {
  getUserIndexAPI().then((res) => {
    console.log(res)
  })
}

//#ifdef APP_PLUS || MP_WEIXIN
onLoad(() => {
  if (userStore.userInfo.token) {
    getUserInfo()
  } else {
    uni.navigateTo({
      url: '/pages/login/login',
    })
  }
})
//#endif
//#ifdef H5
onMounted(() => {
  if (userStore.userInfo.token) {
    getUserInfo()
  } else {
    uni.navigateTo({
      url: '/pages/login/login',
    })
  }
})
//#endif

// Handle user info click - trigger file picker
const handleUserInfo = () => {
  if (filePicker.value) {
    filePicker.value.chooseFiles()
  }
}

// Handle nickname click
const handleNickname = () => {
  // uni.showToast({
  //   title: '点击了昵称设置',
  //   icon: 'none'
  // });
}

// Handle file selection and upload
const handleUpload = (e) => {

  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: function (res) {
      console.log(JSON.stringify(res.tempFilePaths));

      // 创建上传任务
      const uploadTask = uni.uploadFile({
        url: import.meta.env.VITE_SERVER_BASEURL + '/api/common/upload', // 确保这是正确的上传API端点
        filePath: res.tempFilePaths[0],
        name: 'file', // 文件对应的 key，开发者在服务器端通过这个 key 可以获取到文件二进制内容
        formData: {
          name: 'file',
          token: userStore.userInfo.token
        },
        success: (uploadRes) => {
          const result = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data;
          console.log('Upload success:', result);

          if (result.code === 1 && result.data) {
            // 更新用户头像
            console.log(result.data.fullurl)
            let formData = {
              avatar: result.data.fullurl,
              nickname: userStore.userInfo.nickname
            }
            console.log('formData', formData)
            updateUserInfo(formData);
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('Upload failed:', err);
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });

      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        console.log('上传进度', res.progress);
        // 可以在这里添加进度条显示
      });
    }
  });
  // if (e.tempFiles && e.tempFiles.length > 0) {
  //   const tempFilePath = e.tempFiles[0].path || e.tempFiles[0].url

  //   // Upload the file
  //   uni.showLoading({ title: '上传中...' })

  //   postUploadAPI({
  //     fiel: tempFilePath,
  //     name: 'file'
  //   }).then(res => {
  //     if (res.code === 1 && res.data) {
  //       // Update user profile with new avatar URL
  //       const avatarUrl = res.data.url
  //       updateUserAvatar(avatarUrl)
  //     } else {
  //       uni.showToast({
  //         title: '上传失败',
  //         icon: 'none'
  //       })
  //     }
  //     uni.hideLoading()
  //   }).catch(err => {
  //     console.error('Upload error:', err)
  //     uni.hideLoading()
  //     uni.showToast({
  //       title: '上传失败',
  //       icon: 'none'
  //     })
  //   })
  // }
}

// Update user profile with new avatar
const updateUserInfo = (data) => {
  postUpdateProfileAPI(data).then(res => {
    if (res.code === 1) {
      // Update local user info
      userStore.setUserInfo({
        ...userStore.userInfo,
        avatar: data.avatar
      })

      uni.showToast({
        title: '头像更新成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '头像更新失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('Update profile error:', err)
    uni.showToast({
      title: '头像更新失败',
      icon: 'none'
    })
  })
}


</script>

<style>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
  position: relative;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #ffffff;
  margin-top: 20rpx;
}

.info-left {
  font-size: 14px;
  color: #333333;
}

.info-right {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.menu-group {
  margin-top: 20rpx;
  background-color: #ffffff;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
}

.menu-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 14px;
  color: #333333;
}

.item-right {
  display: flex;
  align-items: center;
}

.item-value {
  font-size: 14px;
  color: #999999;
  margin-right: 20rpx;
}

.version {
  font-size: 14px;
  color: #999999;
}

.logout-wrapper {
  margin-top: 60rpx;
  padding: 0 30rpx;
}

.logout-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #1890ff;
  color: #ffffff;
  font-size: 16px;
  border-radius: 44rpx;
}
</style>
<!-- end -->